package com.lcxw.hxzbapi.controller.giftandcubecontroller;

import com.alibaba.fastjson.JSON;
import com.lcxw.hxzbapi.entity.pojo.CubeResult;
import com.lcxw.hxzbapi.entity.pojo.Gift;
import com.lcxw.hxzbapi.entity.pojo.Ticket;
import com.lcxw.hxzbapi.entity.requestBean.GetMyDrawRecordReq;
import com.lcxw.hxzbapi.entity.requestBean.RequestParamBasic;
import com.lcxw.hxzbapi.entity.response.CubeDrawRecordForMem;
import com.lcxw.hxzbapi.service.CubeDrawRecordService;
import com.lcxw.hxzbapi.service.GiftService;
import com.lcxw.hxzbapi.service.TicketService;
import com.lcxw.hxzbcommon.common.StringUtil;
import com.lcxw.hxzbcommon.entity.ErrorCode;
import com.netflix.ribbon.proxy.annotation.ResourceGroup;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import com.alibaba.fastjson.JSONObject;

import javax.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.lcxw.hxzbapi.entity.pojo.Cube;
import com.lcxw.hxzbapi.entity.response.Response;
import com.lcxw.hxzbapi.service.CubeService;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/api/cube")
@Slf4j
public class CubeController {


    @Resource
    CubeService cubeService;

    @Resource
    CubeRealization cubeRealization;

    @Resource
    GiftService giftService;

    @Resource
    GiftRealization giftRealization;
    @Resource
    CubeDrawRecordService cubeDrawRecordService;
    /**
     * 获取魔方的所有可供抽奖的礼物
     */
    @PostMapping("/getAll")
    public Response getAllCube(@RequestBody JSONObject requestParams) {

        long userId = Long.parseLong(requestParams.getString("userId"));
        String type = requestParams.getString("type");
        Response response = new Response();

        Map<String, Object> data = new LinkedHashMap<>();
        List<Cube> cubeList;
        Gift cubeGift = null;
        int ticket = giftRealization.getTicketTimes(userId, type);
        try {
            cubeList = cubeService.selectByType(type);
            if ("luckyCube".equals(type)) {
                cubeGift = giftService.selectByPrimaryKey(2);
            } else if ("diamondCube".equals(type)) {
                cubeGift = giftService.selectByPrimaryKey(3);
            }

        } catch (Exception e) {
            return Response.dbFail(log, "get all cube");
        }
        data.put("cubeList", cubeList);
        data.put("cubeGift", cubeGift);
        data.put("ticket", ticket);
        response.setData(data);
        response.setDesc("success");
        return response;

    }

    /**
     * 获取抽奖公告
     */
    @PostMapping("/draw/record/notice")
    public Response notice(@RequestBody JSONObject requestParams) {
        String type = requestParams.getString("type");
        if(StringUtil.isEmpty(type)){
            return  Response.error(ErrorCode.INVALID_PARAM,"参数错误");
        }
        try {
            List<CubeDrawRecordForMem> list=cubeDrawRecordService.getRecords(type);
            if(!list.isEmpty()){
                for (CubeDrawRecordForMem recordForMem:list){
                    List<CubeDrawRecordForMem> records=cubeDrawRecordService.getLists(recordForMem.getAddTime(),recordForMem.getUserId());
                    String str="";
                    if(!records.isEmpty()){
                        for (int i = 0; i < records.size(); i++) {
                            if(i==0){
                                str=records.get(i).getGiftName()+"*"+records.get(i).getGiftNum();
                            }else {
                                str+=","+records.get(i).getGiftName()+"*"+records.get(i).getGiftNum();
                            }
                        }
                    }
                    recordForMem.setGiftName(str);
                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    if(!StringUtil.isEmpty(recordForMem.getAddTime())){
                        Date date = simpleDateFormat.parse(recordForMem.getAddTime());
                        long diff=(System.currentTimeMillis()-date.getTime())/1000/60;
                        if(diff<=1){
                            recordForMem.setAddTime("刚刚");
                        }else if(diff<=60){
                            recordForMem.setAddTime(diff+"分钟前");
                        }else if(diff>60&diff<1440){
                            recordForMem.setAddTime(diff/60+"小时前");
                        }else if(diff>1440){
                            recordForMem.setAddTime(diff/1440+"天前");
                        }
                    }

                }
            }
            return Response.ok(list);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.dbFail(log, "查询礼物失败");
        }
    }

    /**
     * 魔方抽奖接口
     */
    @PostMapping("/lucky/draw")
    public Response luckyDraw(@RequestBody JSONObject requestParams) {
        long userId = Long.parseLong(requestParams.getString("userId"));
        long roomId = Long.parseLong(requestParams.getString("roomId"));
        String type = requestParams.getString("type");
        int times = Integer.parseInt(requestParams.getString("times"));

        //查用户 type 类型下有多少抽奖次数
        int ticketTimes = giftRealization.getTicketTimes(userId, type);
        if (ticketTimes < times) {
            return Response.error(ErrorCode.INVALID_REQ, "抽奖次数不足");
        }
        JSONObject data = new JSONObject();
        List<CubeResult> cubeList = new ArrayList<>();

        //times次抽奖结果
        try {
            cubeList = cubeRealization.luckyDraw(userId, roomId, type, times);
        } catch (Exception e) {
            return Response.dbFail(log, "数据库操作失败");
        }

        //抽奖结果进行查重
        HashMap<String, CubeResult> map = new HashMap<>();

        for (CubeResult bean : cubeList) {
            if (map.containsKey(bean.getCube().getGiftName())) {
                bean.setNum(map.get(bean.getCube().getGiftName()).getNum() + 1);
            }
            map.put(bean.getCube().getGiftName(), bean);
        }
        cubeList.clear();
        cubeList.addAll(map.values());

        //更新背包里抽中的奖品数量
        cubeRealization.updateGiftBag(userId, cubeList);

        //将中奖记录添加到抽奖记录表中
        cubeRealization.addCubeDrawRecord(userId, cubeList, type, times);

        //减去抽奖用户的抽奖次数
        giftRealization.minusTicket(userId, type, times);

        //抽奖完成后，再查询一下用户剩余的次数
        int ticket = giftRealization.getTicketTimes(userId, type);

        data.put("cubeList", cubeList);
        data.put("ticket", ticket);
        return Response.ok(data);

    }

    /**
     * 获取我的抽奖记录接口
     */
    @PostMapping("/draw/record/get")
    public Response getMyDrawRecord(@RequestBody GetMyDrawRecordReq requestBody) {
        try {
            return cubeRealization.getMyDrawRecord(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return Response.dbFail(log, "查询礼物失败");
        }
    }

    /**
     * 获取中奖排行榜接口
     */
    @PostMapping("/draw/range")
    public Response getDrawRange(@RequestBody RequestParamBasic requestBody) {
        return cubeRealization.getDrawRange();
    }
}
